package kr.or.javacafe.common.web;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoginInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = Logger.getLogger(LoginInterceptor.class);

	public static final String TARGET_URL = "TARGET_URL.LOGIN";

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		HttpSession session = request.getSession();
		String user_id = null;
		synchronized (session) {
			 user_id = (String) session.getAttribute("SESSION_USER_ID");
		}
		
		if (user_id == null) {
			/*
			String requestURI = request.getRequestURI();
			Map parametersMap = request.getParameterMap();
			Iterator keys = parametersMap.keySet().iterator();
			String queryString = "";
			while (keys.hasNext()) {
				String key = (String) keys.next();
				String value = ((String[]) parametersMap.get(key))[0];
				queryString += (key + "=" + value + "&");
			}

			if (queryString.length() > 0) {
				int lastIndex = queryString.lastIndexOf("&");
				queryString = queryString.substring(0, lastIndex);
				requestURI += "?" + queryString;
			}
			*/
			String targetURL = request.getContextPath() + "/USCM/USCM100/uscm100Main.do";

			synchronized (session) {
				session.setAttribute(TARGET_URL, targetURL);
			}
			response.sendRedirect(targetURL);

			return false;
		} 
		else
		{
			return true;
		}
	}

}
